#include <func.h>
#include<string>
#include<string.h>
//创建一个服务端的类
#include<memory>
class HttpServer{
    public :
    HttpServer(const char *ip,const char *port)
    :_ip(ip),_port(port){}
    void Stat()
    {

        _sockfd = socket(AF_INET,SOCK_STREAM,0);//监听socket;
        struct sockaddr_in addr;
        addr.sin_family =AF_INET;
        addr.sin_port = htons(atoi(_port));
        addr.sin_addr.s_addr = inet_addr(_ip);
          

          int reuse = 1;
          setsockopt(_sockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int));
          bind(_sockfd,(struct sockaddr*)&addr,sizeof(addr));
          listen(_sockfd,10);
    }
    void RecvAndShow()
    {
        //取出1条连接
        int netFd = accept(_sockfd,NULL,NULL);
        //使用PAII管理缓冲区动态指针分配内存 自动销毁
        std::unique_ptr<char []>buf(new char[4096]);//buf.get();
        bzero(buf.get(),4096);
        //读取请求的内容，直接显示在stderr中；
        recv(netFd,buf.get(),4096,0);
        fprintf(stderr,"%s\n",buf.get());
        //发送火车头；
        std::string firstLine = "HTTP/1.1 200 OK\r\n";
        send(netFd,firstLine.c_str(),firstLine.size(),0);
        std::string headers = "Content-Type:text/plain\r\n"
                              "Content-Length:5\r\n";
        send(netFd,headers.c_str(),headers.size(),0);
        std::string emptyLine = "\r\n";
        send(netFd,emptyLine.c_str(),emptyLine.size(),0);
        //发送火车车厢；
        std::string body = "hello";
        send(netFd,body.c_str(),body.size(),0);
        //关闭连接
        close(netFd);
        fprintf(stderr,"connection closed\n");
    }
 private:
        const char* _ip;//"192.168.5.128";


        const char* _port;//"1234";
        int _sockfd;     
};